<template>
  <el-dialog
    v-model="formVisible"
    title="修改用户"
    :append-to-body="true"
    @close="closeDialog"
    destroy-on-close
  >
    <el-tabs class="tabs" v-model="activeName">
      <el-tab-pane label="用户信息" name="userInfo">
        <el-form
          :model="userForm"
          :rules="userFormrules"
          ref="userFormRef"
          label-width="80"
          label-position="right"
        >
          <el-form-item label="用户名称" prop="userName">
            <el-input v-model="userForm.userName"></el-input>
          </el-form-item>

          <el-form-item label="姓">
            <el-input v-model="userForm.surname"></el-input>
          </el-form-item>
          <el-form-item label="名">
            <el-input v-model="userForm.name"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="userForm.password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input type="password" v-model="userForm.confirmPassword"></el-input>
          </el-form-item>
          <el-form-item label="邮箱地址" prop="email">
            <el-input v-model="userForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="userForm.phoneNumber"></el-input>
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="userForm.lockoutEnabled"
              >登录失败,账户被锁定</el-checkbox
            >
            <el-checkbox v-model="userForm.isActive">是否激活</el-checkbox>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="角色" name="roleInfo">
        <el-checkbox-group v-model="userForm.roleNames">
          <el-checkbox
            v-for="item in roleList"
            :value="item.name"
            :key="item.id"
            :label="item.name"
          >
          </el-checkbox>
        </el-checkbox-group>
      </el-tab-pane>
      <el-tab-pane label="组织架构" name="orgInfo">
        <el-tree
          v-model="userForm.orgIds"
          node-key="id"
          default-expand-all
          :props="treeProps"
          :data="orgTree"
          show-checkbox
          ref="orgTreeRef"
        />
      </el-tab-pane>
    </el-tabs>
    <div class="modal-footer">
      <el-button type="primary" @click="saveuser">保存</el-button>
    </div>
  </el-dialog>
</template>
<script setup lang="ts">
import { FormInstance, FormRules, TreeInstance } from "element-plus";
import { getAllRoles } from "@/api/identity/role/index";
import { getOrganizationunitForTree } from "@/api/identity/organizationUnits/index";
import {
  getUserinfoById,
  getRolesbyUserId,
  getOrganizationByUserId,
  updateUserToOrg,
} from "@/api/identity/user/index";

const props = defineProps({
  currentItem: { type: Object, default: null },
});
const formVisible = ref<Boolean>(true);
const activeName = ref<string>("");
activeName.value = "userInfo";
const userFormRef = ref<FormInstance>();
const userForm = ref<any>({});
const orgTreeRef = ref<TreeInstance>();
const roleList = ref<any>([]);
const orgTree = ref<any>([]);
const treeProps = {
  children: "child",
  label: "displayName",
};

const confirmPasswordRule = (rule: any, value: any, callback: any) => {
  //debugger
  if (value != ""&&value != userForm.value.password) {
      callback(new Error("两次输入密码不一致!"));
  }else
  {
    callback();
  } 
};
const userFormrules = ref<FormRules>({
  userName: [{ required: true, message: "请输入用户名称", trigger: "blur" }],
  confirmPassword: [{ validator: confirmPasswordRule, trigger: "blur" }],
  email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
});
const emit = defineEmits(["closedialogevent", "refresh"]);
const getOrgTree = async () => {
  orgTree.value = await getOrganizationunitForTree({});
};

const getRoles = async () => {
  roleList.value = (await getAllRoles()).items;
};
const getUserInfo = async () => {
  let userinfo = await getUserinfoById(props.currentItem.id);
  userForm.value = { ...userinfo };

  let userRole = (await getRolesbyUserId(props.currentItem.id)).items;
  if (userRole != null && userRole.length > 0) {
    userForm.value.roleNames = userRole.map((ri) => ri.name);
  }
  let userOrg = (await getOrganizationByUserId(props.currentItem.id)).items;
  if (userOrg != null && userOrg.length > 0) {
    let orgList = userOrg.map((org) => org.id);
    orgTreeRef.value!.setCheckedKeys(orgList);
  }
};

const pg_init = () => {
  getOrgTree();
  getRoles();
  getUserInfo();
};
const closeDialog = () => {
  formVisible.value = false;
  emit("closedialogevent", formVisible.value);
};

const saveuser = () => {
  userFormRef.value?.validate((valid, fields) => {
    if (valid) {
      let checkNodes = orgTreeRef.value?.getCheckedNodes();
      let param = userForm.value;
      param.orgIds = checkNodes.map((item: any) => {
        return item.id;
      });
      updateUserToOrg(props.currentItem.id, param).then((res) => {
        if (res) {
          ElNotification({
            title: "提示",
            message: "修改用户成功",
            type: "success",
            duration: 2000,
          });
          closeDialog();
          emit("refresh");
        } else {
          closeDialog();
          return false;
        }
      });
    }
  });
};

onMounted(() => {
  pg_init();
});
</script>
